﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Login.Controllers
{
    public class CookieController : Controller
    {

        //表单
        public IActionResult Index()
        {
            return View();
        }

        //接收表单提交的数据
        public ActionResult Login(LoginViewModel model)
        {
            SetCookies("UserName", model.UserName);
            SetCookies("PassWord", model.PassWord);
            return RedirectToAction("Hello");
        }

        //重定向到这个页面
        public ActionResult Hello()
        {
            ViewBag.UserName = GetCookies("UserName");
            ViewBag.PassWord = GetCookies("PassWord");
            return View();
        }

        void SetCookies(string key, string value, int minutes = 30)
        {
            if (string.IsNullOrEmpty(value))
            {
                value = "";
            }
            HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes),
                IsEssential = true
            });
        }

        string GetCookies(string key)
        {
            return HttpContext.Request.Cookies[key];
        }

    }
}
